import Foundation

class WallpaperScheduler {
    static let shared = WallpaperScheduler()
    
    struct Schedule: Codable {
        let id: UUID
        let name: String
        let preset: WallpaperPreset.Preset
        let startTime: Date
        let repeatType: RepeatType
        var isEnabled: Bool
    }
    
    enum RepeatType: String, Codable {
        case once
        case daily
        case weekly
        case monthly
    }
    
    private var schedules: [Schedule] = []
    private let schedulesURL: URL
    private var timers: [UUID: Timer] = [:]
    
    private init() {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        schedulesURL = documentsDirectory.appendingPathComponent("wallpaper_schedules.json")
        loadSchedules()
        setupTimers()
    }
    
    private func loadSchedules() {
        guard let data = try? Data(contentsOf: schedulesURL) else { return }
        schedules = (try? JSONDecoder().decode([Schedule].self, from: data)) ?? []
    }
    
    private func saveSchedules() {
        guard let data = try? JSONEncoder().encode(schedules) else { return }
        try? data.write(to: schedulesURL)
    }
    
    private func setupTimers() {
        // 清除所有现有的定时器
        timers.values.forEach { $0.invalidate() }
        timers.removeAll()
        
        // 为每个启用的计划创建定时器
        for schedule in schedules where schedule.isEnabled {
            createTimer(for: schedule)
        }
    }
    
    private func createTimer(for schedule: Schedule) {
        let now = Date()
        var nextDate = schedule.startTime
        
        // 计算下一次执行时间
        while nextDate < now {
            switch schedule.repeatType {
            case .once:
                return  // 如果是一次性任务且已过期，则不创建定时器
            case .daily:
                nextDate = Calendar.current.date(byAdding: .day, value: 1, to: nextDate) ?? nextDate
            case .weekly:
                nextDate = Calendar.current.date(byAdding: .weekOfYear, value: 1, to: nextDate) ?? nextDate
            case .monthly:
                nextDate = Calendar.current.date(byAdding: .month, value: 1, to: nextDate) ?? nextDate
            }
        }
        
        let timer = Timer(fire: nextDate, interval: 0, repeats: false) { [weak self] _ in
            WallpaperPreset.shared.applyPreset(schedule.preset)
            self?.handleScheduleCompletion(schedule)
        }
        
        RunLoop.main.add(timer, forMode: .common)
        timers[schedule.id] = timer
    }
    
    private func handleScheduleCompletion(_ schedule: Schedule) {
        switch schedule.repeatType {
        case .once:
            if let index = schedules.firstIndex(where: { $0.id == schedule.id }) {
                schedules[index].isEnabled = false
                saveSchedules()
            }
        default:
            // 为重复性任务创建下一次的定时器
            createTimer(for: schedule)
        }
    }
    
    func createSchedule(name: String, preset: WallpaperPreset.Preset, startTime: Date, repeatType: RepeatType) -> Schedule {
        let schedule = Schedule(
            id: UUID(),
            name: name,
            preset: preset,
            startTime: startTime,
            repeatType: repeatType,
            isEnabled: true
        )
        schedules.append(schedule)
        saveSchedules()
        createTimer(for: schedule)
        return schedule
    }
    
    func deleteSchedule(_ schedule: Schedule) {
        timers[schedule.id]?.invalidate()
        timers.removeValue(forKey: schedule.id)
        schedules.removeAll { $0.id == schedule.id }
        saveSchedules()
    }
    
    func toggleSchedule(_ schedule: Schedule) {
        if let index = schedules.firstIndex(where: { $0.id == schedule.id }) {
            schedules[index].isEnabled.toggle()
            if schedules[index].isEnabled {
                createTimer(for: schedules[index])
            } else {
                timers[schedule.id]?.invalidate()
                timers.removeValue(forKey: schedule.id)
            }
            saveSchedules()
        }
    }
    
    func getAllSchedules() -> [Schedule] {
        return schedules
    }
    
    func getActiveSchedules() -> [Schedule] {
        return schedules.filter { $0.isEnabled }
    }
}